import React, { useState, useRef } from 'react'
import { Space, Table, Button, Input } from 'antd'
import * as XLSX from 'xlsx'
function Com() {
  const fileRef = useRef()
  const [proList, setProList] = useState([])
  const columns = [
    {
      title: '序号',
      render (text, record, index) {
        return <span>{ index + 1 }</span>
      }
    },
    {
      title: '商品名称',
      dataIndex: 'proname'
    }
  ]
  const upload = () => {
    const file = fileRef.current.input.files[0]
    const reader = new FileReader()
    reader.readAsBinaryString(file) // 二进制
    reader.onload = function () {
      const workbook = XLSX.read(this.result, { type: 'binary' });
      const t = workbook.Sheets['工作表1']
      const r = XLSX.utils.sheet_to_json(t)
      // 如果需要调用接口上传到服务器
      setProList(r)
    }
  }
  return (
    <div>
      <h1>导入数据</h1>
      <Space style={{ width: '100%' }} direction="vertical">
        <Button onClick ={ () => { fileRef.current.input.click() }}>上传商品</Button>
        <Input hidden ref = { fileRef } type="file" onChange = { upload }></Input>
        <Table 
          dataSource = { proList }
          columns = { columns }
          rowKey="proid"
        />
      </Space>
    </div>
  )
}

export default Com


